﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using UTC_Project_Manager.Model.Infrastructure;
using System.Net.Mail;
using System.Net;

namespace UTC_Project_Manager.Controls
{
    /// <summary>
    /// Interaction logic for NewReunionControl.xaml
    /// </summary>
    public partial class NewReunionControl : UserControl
    {
        private List<Member> members;
        private bool dateSet, titleSet;
        public delegate void NewReunionEvent(Meeting meeting);
        public static event NewReunionEvent newReunionCreatedEvent;

        public delegate void EmptyDescriptionEvent(Boolean isNewMeeting);
        public static event EmptyDescriptionEvent emptyDescription;


        public delegate void StartMeetingEvent();
        public static event StartMeetingEvent newStartMeetingEvent;


        public NewReunionControl()
        {
            InitializeComponent();
            IsInit = true;
            PopulateMembers();
            members = new List<Member>();
            this.saveButton.IsEnabled = false;
            IsInit = false;
            dateSet = false;
            titleSet = false;
            IsFinalized = false;
        }

        public Meeting CurrentMeeting
        {
            get;
            private set;
        }

        private void PopulateMembers()
        {
            
            foreach (Member member in App.MyConfig.OurProject.Members)
            {
                CheckBox cb = new CheckBox();
                cb.IsChecked = false;
                cb.Checked += new RoutedEventHandler(cb_Checked);
                cb.Unchecked += new RoutedEventHandler(cb_Unchecked);
                cb.VerticalAlignment = VerticalAlignment.Center;
                cb.Name = member.ToString().Replace(" ", "");
                Label lab = new Label();
                lab.VerticalAlignment = VerticalAlignment.Center;
                lab.FontSize = 14;
                lab.Content = member.ToString();
                StackPanel spanel = new StackPanel();
                spanel.Orientation = Orientation.Horizontal;
                spanel.Children.Add(cb);
                spanel.Children.Add(lab);
                ListBoxItem lbi = new ListBoxItem();
                lbi.Content = spanel;
                this.membersListBox.Items.Add(lbi);
                
            }
        }

        void cb_Unchecked(object sender, RoutedEventArgs e)
        {
            CheckBox currentCB = sender as CheckBox;
            foreach (Member member in App.MyConfig.OurProject.Members)
                if (currentCB.Name.Equals(member.ToString().Replace(" ", "")))
                    members.Remove(member);
            if (IsFinalized && ! IsInit)
            {
                this.startButton.IsEnabled = false;
                this.saveButton.IsEnabled = true;
                this.cancelButton.IsEnabled = true;
            }

        }

        void cb_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox currentCB = sender as CheckBox;
            foreach(Member member in App.MyConfig.OurProject.Members)
                if (currentCB.Name.Equals(member.ToString().Replace(" ","")))
                    members.Add(member);

            if (IsFinalized && !IsInit)
            {
                this.startButton.IsEnabled = false;
                this.saveButton.IsEnabled = true;
                this.cancelButton.IsEnabled = true;
            }
        }

        private void EnableButtons()
        {
            this.saveButton.IsEnabled = true;
            this.cancelButton.IsEnabled = true;
        }

        private void DisableButtons()
        {
            this.saveButton.IsEnabled = false;
            this.cancelButton.IsEnabled = false;
        }

        private void saveButton_Click(object sender, RoutedEventArgs e)
        {
            CurrentMeeting = new Meeting();
            CurrentMeeting.Invited = members;
            CurrentMeeting.Title = this.titleTextBox.Text;
            CurrentMeeting.Description = this.descriptionTextBox.Text;
            CurrentMeeting.Points = this.pointsTextBox.Text;
            DateTime dateTime = (DateTime)this.meetingDatePicker.SelectedDate;
            TimeSpan time = (TimeSpan)this.meetingTimePicker.SelectedTime;
            CurrentMeeting.Date = new DateTime(dateTime.Year, dateTime.Month, dateTime.Day, time.Hours, time.Minutes, time.Seconds);
            //If we are editing the event, we need to remove the current event and replace it
            App.MyConfig.OurProject.Meetings.Add(CurrentMeeting);
            // Send the event
            
            newReunionCreatedEvent(CurrentMeeting);
            
            SendMail();
            DisableButtons();
            this.startButton.Visibility = Visibility.Visible;
            this.startButton.IsEnabled = true;
            IsFinalized = true;
        }

        public Boolean IsInit
        { get; set; }

        public Boolean IsFinalized
        { get; set; }

        private void SendMail()
        {
            MailSettings settings = App.MyConfig.OurProject.Smtp;
            String sender = App.MyConfig.OurProject.Email;
            if (sender != null && settings != null)
            {
                foreach (Member member in members)
                {
                    MailMessage mail = new MailMessage(sender, member.Email);
                    mail.Subject = "[UTC ProjectManager] Nouvelle Réunion le " + CurrentMeeting.Date.ToString();
                    mail.Body = "Titre: " +CurrentMeeting.Title + "\r\n";
                    mail.Body += "Description:\r\n\t" + CurrentMeeting.Description + "\r\n";
                    mail.Body += "Agenda:\r\n\t" + CurrentMeeting.Points + "\r\n";
                    SmtpClient client = new SmtpClient(settings.Smtp, settings.Port);
                    if (settings.IsAnonymous)
                        client.Credentials = CredentialCache.DefaultNetworkCredentials;
                    else
                        client.Credentials = new NetworkCredential(settings.Login, settings.Password);
                    try
                    {
                        client.Send(mail);
                    }
                    catch (Exception ex) { }
                }
                
            }
        }

        private void titleTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!IsInit)
            {
                if (!IsFinalized)
                {
                    if (this.titleTextBox.Text != "")
                        titleSet = true;
                    if (dateSet)
                        this.saveButton.IsEnabled = true;
                    this.startButton.IsEnabled = false;
                }
                else
                    if (this.titleTextBox.Text != "" && this.meetingDatePicker.SelectedDate != new DateTime(0001, 01, 01))
                    {
                        EnableButtons();
                        this.startButton.IsEnabled = false;
                    }
            }

        }

        private void meetingDatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!IsInit)
            {
                if (this.meetingDatePicker.SelectedDate != new DateTime(0001, 01, 01))
                    dateSet = true;
                if (titleSet)
                    this.saveButton.IsEnabled = true;
                this.startButton.IsEnabled = false;
            }
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (!IsFinalized)
            {
                // empty the description Control
                emptyDescription(true);

            }
            else
            {
                //revert changes
                emptyDescription(false);

            }
                
            this.startButton.IsEnabled = true;
            DisableButtons();
        }

        private void meetingTimePicker_SelectedTimeChanged(object sender, AC.AvalonControlsLibrary.Controls.TimeSelectedChangedRoutedEventArgs e)
        {
            if (!IsInit)
            {
                this.startButton.IsEnabled = false;
                EnableButtons();
            }
        }

        private void descriptionTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (!IsInit)
            {
                this.startButton.IsEnabled = false;
                EnableButtons();
            }
        }

        private void startButton_Click(object sender, RoutedEventArgs e)
        {
            
            newStartMeetingEvent();
        }

        public void CheckMembers(List<Member> invited)
        {
            foreach (ListBoxItem item in this.membersListBox.Items)
            {
                StackPanel spanel = item.Content as StackPanel;
                CheckBox cb = spanel.Children[0] as CheckBox;
                foreach (Member m in invited)
                {
                    if (m.ToString().Replace(" ", "").Equals(cb.Name))
                        cb.IsChecked = true;
                }
            }
        }
    }
}
